package gui;

import java.awt.EventQueue;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import javax.swing.JButton;
import common.Static;

import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.visualization.VisualizationViewer;

import optimizers.ganeat.Individual;
import optimizers.ganeat.square.IndividualSquare;
import util.MyUtil;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import javax.swing.JScrollPane;
import java.awt.GridLayout;
import java.awt.Color;

public class ExportEvolutionToImagesTool extends JFrame implements
		ActionListener {

	private JPanel contentPane;
	private Individual indiv;
	VisualizationViewer<String, String> vv;
	private JPanel panel_1;
	private JScrollPane scrollPane;
	private JButton btnFixLocation;
	private VisualizationViewer[] aVV;
	private JPanel[] timeSeries;
	private JPanel[] panels;

	public ExportEvolutionToImagesTool(String title, final Individual indiv) {
		setTitle(title);
		this.indiv = indiv;
		setBounds(100, 100, 830, 395);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 11, 800, 300);
		contentPane.add(scrollPane);

		panel_1 = new JPanel();
		scrollPane.setViewportView(panel_1);
		panel_1.setLayout(new GridLayout(0, 1, 0, 0));

		JButton btnExport = new JButton("Export");
		btnExport.addActionListener(this);
		btnExport.setBounds(221, 322, 89, 23);
		contentPane.add(btnExport);

		JPanel panel_2 = new JPanel();
		panel_2.setBackground(Color.WHITE);
		panel_2.setLayout(new FlowLayout());
		vv = (VisualizationViewer<String, String>) indiv.getOligoModel()
				.getVisualization(250, 250);
		panel_2.add(vv);
		panel_2.add(indiv.displayTimeSeries());
		panel_1.add(panel_2);

		btnFixLocation = new JButton("Fix Location");
		btnFixLocation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final Map<String, java.awt.geom.Point2D> locs = new HashMap<String, java.awt.geom.Point2D>();
				Layout<String, String> layout = vv.getGraphLayout();
				for (String v : layout.getGraph().getVertices()) {
					java.awt.geom.Point2D p = layout.transform(v);
					locs.put(v, p);
				}

				final Stack<Individual> stack = new Stack<Individual>();
				Individual tmp = indiv;
				do {
					stack.push(tmp);
					double parent1Fitness;
					try {
						parent1Fitness = (tmp.parent1 == null ? Double.MIN_VALUE
								: tmp.parent1.fitnessResult.finalResult());
					} catch (Exception ex) {
						parent1Fitness = Double.MIN_VALUE;
					}
					double parent2Fitness;
					try {
						parent2Fitness = (tmp.parent2 == null ? Double.MIN_VALUE
								: tmp.parent2.fitnessResult.finalResult());
					} catch (Exception ex) {
						parent2Fitness = Double.MIN_VALUE;
					}
					if (parent1Fitness > parent2Fitness) {
						tmp = tmp.parent1;
					} else {
						tmp = tmp.parent2;
					}
				} while (tmp != null);
				System.out.println("Done, stack size = " + stack.size());
				aVV = new VisualizationViewer[101];
				panels = new JPanel[101];
				timeSeries = new JPanel[101];

				int current = 0;
				while (!stack.isEmpty()) {
					Individual indiv = stack.pop();
					int to = indiv.generationIndex + 1;
					if (stack.isEmpty()) {
						to = 100;
					}
					for (int j = current; j < to; j++) {
						aVV[j] = (VisualizationViewer) indiv.getOligoModel()
								.getVisualization(250, 250, locs);
						timeSeries[j] = indiv.displayTimeSeries("Generation "
								+ (j + 1));
						System.out.println("Complete " + (j + 1) + "/"
								+ aVV.length);
					}
					current = to;
				}
				IndividualSquare indiv = new IndividualSquare(
						new HashMap<String, Integer>(),
						new HashMap<String, String>(), 0, 0, null,
						Static.prototypes.get("Simplest"));
				aVV[100] = (VisualizationViewer) indiv.getOligoModel()
						.getVisualization(250, 250, locs);
				timeSeries[100] = indiv.displayTimeSeries("Generation 0");
				for (int i = 0; i < panels.length; i++) {
					panels[i] = new JPanel();
					panels[i].setBackground(Color.WHITE);
					panels[i].setLayout(new FlowLayout());
					System.out.println(i);
					panels[i].add(aVV[i]);
					panels[i].add(timeSeries[i]);
					panel_1.add(panels[i]);
				}
				panel_1.revalidate();
			}
		});
		btnFixLocation.setBounds(10, 322, 149, 23);
		contentPane.add(btnFixLocation);
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ExportEvolutionToImagesTool frame = new ExportEvolutionToImagesTool(
							"Test", new Individual(
									new HashMap<String, Integer>(),
									new HashMap<String, String>(), 0, 0, null,
									Static.prototypes.get("Oligator")));
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */

	@Override
	public void actionPerformed(ActionEvent arg0) {
		int result;
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new java.io.File("."));
		chooser.setDialogTitle("Select directory for exportation");
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		//
		// disable the "All files" option.
		//
		chooser.setAcceptAllFileFilterUsed(false);
		//
		if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

			System.out.println("getSelectedFile() : "
					+ chooser.getSelectedFile());
			for (int i = 0; i < panels.length; i++) {
				MyUtil.createImage(panels[i], chooser.getSelectedFile()
						+ "\\Topol" + (i + 1) + ".png", 800, 320);
			}
			/*
			 * Individual tmp = indiv; do { Properties p = new Properties();
			 * p.setProperty("PageSize", "A5"); VectorGraphics g; try { g = new
			 * GIFGraphics2D(new File("Topol_gen" + tmp.generationIndex +
			 * ".gif"), new Dimension(250, 250)); g.setProperties(p);
			 * g.startExport(); vv.print(g); g.endExport(); } catch
			 * (FileNotFoundException e) { // TODO Auto-generated catch block
			 * e.printStackTrace(); } double parent1Fitness = (tmp.parent1 ==
			 * null ? Double.MIN_VALUE :
			 * tmp.parent1.fitnessResult.finalResult()); double parent2Fitness =
			 * (tmp.parent2 == null ? Double.MIN_VALUE :
			 * tmp.parent2.fitnessResult.finalResult()); if (parent1Fitness >
			 * parent2Fitness) { tmp = tmp.parent1; } else { tmp = tmp.parent2;
			 * } } while (tmp != null);
			 */
		} else {
			System.out.println("No Selection ");
		}

	}
}
